package com.iams.manage.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.iams.manage.service.IDocumentService;
import com.iams.common.utils.SearchContextHolder;
import com.iams.manage.service.IElasticsearchArchiveService;
import com.iams.manage.domain.Document;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.iams.common.annotation.Log;
import com.iams.common.core.controller.BaseController;
import com.iams.common.core.domain.AjaxResult;
import com.iams.common.enums.BusinessType;
import com.iams.manage.domain.Archive;
import com.iams.manage.service.IArchiveService;
import com.iams.common.utils.poi.ExcelUtil;
import com.iams.common.core.page.TableDataInfo;

import com.iams.elasticsearch.domain.ElasticsearchArchive;

/**
 * 档案列表Controller
 *
 * @author zhjm
 * @date 2025-01-10
 */
@RestController
@RequestMapping("/manage/archive")
public class ArchiveController extends BaseController
{
    @Autowired
    private IArchiveService archiveService;

    @Autowired
    private IDocumentService documentService;

    @Autowired
    private IElasticsearchArchiveService ElasticsearchArchiveService;

    /**
     * 查询档案列表列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:list')")
    @GetMapping("/list")
    public TableDataInfo list(Archive archive)
    {
        startPage();
        List<Archive> list = archiveService.selectArchiveList(archive);
        return getDataTable(list);
    }


    /**
     * 全文检索：内容
     */
    @GetMapping("/Elasticsearch")
    public TableDataInfo contentList(@RequestParam Map<String, String> allParams)
    {
        startPage();
        List<ElasticsearchArchive> list = ElasticsearchArchiveService.CombineSearch(allParams);

        // 获取受限记录数
        int restrictedCount = SearchContextHolder.getAndClearRestrictedCount();

        // 构建返回结果
        TableDataInfo dataTable = getDataTable(list);
        if (restrictedCount > 0) {
            dataTable.setMsg("您有 " + restrictedCount + " 条记录因权限限制无法查看");
        }
        return dataTable;
    }



    // 根据 mysqlDanghao 获取档案的 id
    @GetMapping("/get-id-by-mysql-danghao")
    @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    public  ResponseEntity<Map<String, Object>> getArchiveIdByMysqlDanghao(@RequestParam String mysqlDanghao) {
        Long archiveId = archiveService.getArchiveIdByMysqlDanghao(mysqlDanghao);
        if (archiveId != null) {
//            return ResponseEntity.ok(archiveId);
//            把 archiveId 封装到 result 中，直接使用 Map 来构造返回值
            Map<String, Object> result = new HashMap<>();
            result.put("data", archiveId);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @GetMapping("/get-location-by-mysql-danghao")
    // @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    public  ResponseEntity<Map<String, Object>> getArchiveLocationByDanghao(@RequestParam String mysqlDanghao) {
        String location = archiveService.getArchiveLocationByDanghao(mysqlDanghao);
        if (location != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("data", location);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }


    /**
     * 导出档案列表列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:export')")
    @Log(title = "档案列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Archive archive)
    {
        List<Archive> list = archiveService.selectArchiveList(archive);
        ExcelUtil<Archive> util = new ExcelUtil<Archive>(Archive.class);
        util.exportExcel(response, list, "档案列表数据");
    }

    /**
     * 获取档案列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        if(archiveService.checkArchivePermission(id))
        {
            return success(archiveService.selectArchiveById(id));
        }
        else return AjaxResult.error("权限不足");
    }

    /**
     * 获取档案权限
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    @GetMapping(value = "/permission/{id}")
    public AjaxResult getPermissionInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(archiveService.checkArchivePermission(id));
    }



    /**
     * 新增档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:add')")
    @Log(title = "档案列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Archive archive)
    {
        return toAjax(archiveService.insertArchive(archive));
    }

    /**
     * 修改档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:edit')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Archive archive)
    {
        return toAjax(archiveService.updateArchive(archive));
    }

    /**
     * 删除档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:remove')")
    @Log(title = "档案列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(archiveService.deleteArchiveByIds(ids));
    }

    /**
     * 新增档案文件列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:edit')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PutMapping("/directory")
    public AjaxResult addDirectoryFiles(@RequestBody Document document)
    {
        return toAjax(archiveService.addDirectoryFiles(document));
    }

    /**
     * 删除档案文件列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:edit')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PutMapping("/directory/delete")
    public AjaxResult deleteDirectoryFiles(@RequestBody Document document) {
        return toAjax(archiveService.deleteDirectoryFiles(document));
    }

    /**
     * 根据location查询档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:list')")
    @GetMapping("/location")
    public TableDataInfo getArchiveByLocation(@RequestParam String location) {
        List<Archive> list = archiveService.getArchiveByLocation(location);
//        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 拖拽移动档案
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:move')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PostMapping("/move")
    public AjaxResult moveArchive(@RequestBody Map<String, Object> requestParams) {
        Long archiveId = Long.parseLong(requestParams.get("archiveId").toString());
        String targetLocation = requestParams.get("targetLocation").toString();
        return toAjax(archiveService.moveArchive(archiveId, targetLocation));
    }

    /**
     * 档案全部下架
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:update')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PostMapping("/updateLocation")
    public AjaxResult takeOff(@RequestBody List<Archive> archives) {
        return toAjax(archiveService.takeOffArchives(archives));
    }

    /**
     * 获取未上架的档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:list')")
    @GetMapping("/upArchiveList")
    public TableDataInfo getUpArchiveList(@RequestParam Map<String, Object> query) {
        startPage();
        List<Archive> list = archiveService.getUpArchiveList(query);
        return getDataTable(list);
    }

    // 生成档号需要
    @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    @GetMapping("/get-next-archive-number")
    public AjaxResult getNextArchiveNumber(@RequestParam Long id ) {
        java.util.Random random = new java.util.Random(id);
        String nextArchiveNumber = String.valueOf(random.nextInt(10000)); // 使用id作为种子生成一个0到9999之间的随机数
        return AjaxResult.success(nextArchiveNumber);
    }

    // 文档批量挂接的接口
    @PreAuthorize("@ss.hasPermi('manage:archive:edit')")
    @Log(title = "档案列表", businessType = BusinessType.UPDATE)
    @PostMapping("/batch-mount")
    public AjaxResult batchMount(@RequestBody Map<String, Object> data) {
        // {docIds={docIds=[38], directoryId=1}}
        // 获取 docIds 对象
        Map<String, Object> docIdsMap = (Map<String, Object>) data.get("docIds");

        // 从 docIds 对象中获取 docIds 数组
        List<Integer> docIds = (List<Integer>) docIdsMap.get("docIds");

        // 获取 directoryId
        Integer directoryId = (Integer) docIdsMap.get("directoryId");

        for (Integer docId : docIds) {
            // 得到修改目录前文档对象
            Document document = documentService.selectDocumentById(docId.longValue());
            // 在档案目录中删除原文档id
            archiveService.deleteDirectoryFiles(document);
            // 更新文档id
            document.setDirectory(directoryId.longValue());
            // 更新文档
            documentService.updateDocument(document);
            // 在档案目录中添加新文档id
            archiveService.addDirectoryFiles(document);
        }
        return AjaxResult.success(data.size());
    }
}
